let express = require('express');
let router = express.Router();
var user = require('../database/db').user;
/* GET users listing. */
var mongodb = require('mongodb')
var MongoClient = require('mongodb').MongoClient;
var DB_CONN_STR = 'mongodb://localhost:27017/ET';
let users = [
    {
        id: 1,
        name: 'fdy',
        pwd: '1'
    },
    {
        id: 2,
        name: 'qwe',
        pwd: '1'
    }
]
//获取用户
router.get('/', function (req, res, next) {
    var selectData = function (db, callback) {
        //连接到表
        var collection = db.collection('users');
        //查询数据
        var whereStr = {"name": 'password'};
        collection.find(whereStr, function (error, cursor) {
            cursor.each(function (error, doc) {
                if (doc) {
                    console.log(doc);

                }
            });

        });
    }

    MongoClient.connect(DB_CONN_STR, function (err, db) {
        console.log("连接成功！");
        selectData(db, function (result) {
            console.log(result);
            db.close();
        });
    });
    res.send(JSON.stringify(users));
});
//新增用户
router.post('/', function (req, res, next) {
    users = users.concat(req.body);
    res.send(JSON.stringify(users));
});
//更新用户
router.put('/:id', function (req, res, next) {
    for (let i = 0; i < users.length; i++) {
        if (users[i].id === parseInt(req.params.id)) {
            users[i] = req.body
        }
    }
    res.send(JSON.stringify(users));
})
//删除用户
router.delete('/:id', function (req, res, next) {
    for (let i = 0; i < users.length; i++) {
        if (users[i].id === parseInt(req.params.id)) {
            users.splice(i, 1)
        }
    }
    res.send("Success");

})
module.exports = router;
